//
//  ZMPurchaseTableViewController.swift
//  MyProject
//
//  Created by mingzhao on 15/4/2.
//  Copyright (c) 2015年 mingzhao. All rights reserved.
//

import UIKit
import StoreKit

class ZMPurchaseTableViewController: UITableViewController,SKPaymentTransactionObserver,SKProductsRequestDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Potentially incomplete method implementation.
        // Return the number of sections.
        return 0
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete method implementation.
        // Return the number of rows in the section.
        return 0
    }

    /*
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as UITableViewCell

        // Configure the cell...

        return cell
    }
    */

    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        self.testBuy()
    }
    
    
    func testBuy(){
        if SKPaymentQueue.canMakePayments() {
            self.getProductInfo("VipMonth")
        }
        else{
            NSLog("失败，用户禁止应用内付费购买.")
        }
    }
    
    func getProductInfo(proid : String)->Void {
        var set = NSSet(array: [proid])
        var request = SKProductsRequest(productIdentifiers: set)
        request.delegate = self
        request.start()
    }
    
    //MARK: SKProductsRequestDelegate
    func productsRequest(request: SKProductsRequest!, didReceiveResponse response: SKProductsResponse!) {
        var myproduct = response.products
        if myproduct.count == 0 {
            NSLog("无法获取产品信息，购买失败。");
            return;
        }
        
        var payment = SKPayment(product: myproduct[0] as SKProduct)
        SKPaymentQueue.defaultQueue().addPayment(payment)
    }
    
    //MARK:SKPaymentTransactionObserver
    func paymentQueue(queue: SKPaymentQueue!, updatedTransactions transactions: [AnyObject]!) {
        var msg:String?
        for trans in transactions {
            if let transaction = trans as? SKPaymentTransaction {
                switch transaction.transactionState {
                case SKPaymentTransactionState.Purchased://交易失败
                    NSLog("transactionIdentifier = %@", transaction.transactionIdentifier);
                    self.completeTransaction(transaction)
                case .Failed://交易失败
                    NSLog("交易失败")
                    self.failedTransaction(transaction)
                case .Restored://已经购买过该商品
                    NSLog("已经购买过该商品")
                    self.restoreTransaction(transaction)
                case .Purchasing://商品添加进列表
                    NSLog("商品添加进列表")
                    msg = "商品添加进列表"
                    //                    SKPaymentQueue.defaultQueue().finishTransaction(transaction)
                default:
                    msg = "交易失败"
                    NSLog("默认操作")
                }
            }
        }
    }
    
    func completeTransaction(transaction:SKPaymentTransaction)->Void {
        var productIdentifier = transaction.payment.productIdentifier
        var state = transaction.transactionState
        var transaction_id = transaction.transactionIdentifier
        if state == SKPaymentTransactionState.Purchased {
            // 向自己的服务器验证购买凭证
            NSLog("向自己的服务器验证购买凭证: %@", productIdentifier)
            NSLog("transaction_id: %@", transaction_id)
            if let receiptUrl = NSBundle.mainBundle().appStoreReceiptURL {
                if let receiptData = NSData(contentsOfURL:receiptUrl) {
                    var receipt_data = receiptData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.allZeros)
                    
                    NSLog("receipt: %@", receipt_data)
                    
//                    //这是去官网验证此次付费的成功与否，一般放在服务器执行
//                    var paras = ["receipt-data": receipt_data]
//                    Alamofire.request(.POST, "https://sandbox.itunes.apple.com/verifyReceipt", parameters:paras, encoding:ParameterEncoding.JSON)
//                        .responseJSON({ (request, response, json, error) -> Void in
//                            if error == nil {
//                                if let data = json as? NSDictionary {
//                                    NSLog("return json: %@", data)
//                                }
//                            }
//                        })
                }
            }
        }
        
        SKPaymentQueue.defaultQueue().finishTransaction(transaction)
    }
    
    func failedTransaction(transaction:SKPaymentTransaction)->Void {
        var msg = "用户取消交易"
        if transaction.error.code != SKErrorPaymentCancelled {
            msg = "购买失败"
            NSLog("购买失败");
        }
        else {
            NSLog("用户取消交易");
        }
        
        SKPaymentQueue.defaultQueue().finishTransaction(transaction)
    }
    
    func restoreTransaction(transaction:SKPaymentTransaction)->Void {
        // 对于已购商品，处理恢复购买的逻辑
        SKPaymentQueue.defaultQueue().finishTransaction(transaction)
    }

}
